package com.wang.tool.monitor.writer;

import com.wang.tool.monitor.LinkLogUtil;
import com.wang.tool.monitor.core.MonitorInfo;
import com.wang.tool.util.SimpleLogUtil;

/**
 * 全局监控输出器
 * 为什么单独设计一个类管理监控输出?
 * 我们有InvokeTemplate,需要静态取用
 *
 * @Author wangshaopeng
 * @Date 2022/6/28
 */
public class GlobalMonitorWriter {


    /**
     * 全局配置
     */
    private static MonitorWriter writer = new SimpleMonitorWriter();

    /**
     * 输出监控
     * 不会抛错
     *
     * @param monitorInfo
     */
    public static void write(MonitorInfo<?> monitorInfo) {
        try {
            if (writer == null) {
                return;
            }
            writer.write(monitorInfo);
        } catch (Throwable e) {
            LinkLogUtil.newTagLog(MonitorInfo.TAG_MONITOR_ERROR)
                    .v1(monitorInfo.getBiz() + ":" + monitorInfo.getAction())
                    .v2("write")
                    .pointLink(monitorInfo.getLink())
                    .addAttachment(MonitorInfo.ERROR, e)
                    .log();
        }
    }

    /**
     * 设置全局监控输出器
     *
     * @param writer
     */
    public static void setWriter(MonitorWriter writer) {
        GlobalMonitorWriter.writer = writer;
        SimpleLogUtil.info("[changeGlobalMonitorWriter] writer:{0}", writer);
    }


}
